package com.lwj.consumer;

import com.lwj.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.concurrent.ExecutionException;

/**
 * @Author: lwj
 * @Date: 2019/4/10 0010 10:13
 * @Description:
 */
@RestController
public class ConsumerController {

    @Autowired
    private LoadBalancerClient loadBalancerClient; // Balancer 平衡器
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HelloService helloService;


    @RequestMapping(value = "/consumer")
    public String helloConsumer() throws ExecutionException, InterruptedException {
        //这里根据配置文件的那个providers属性取的
        ServiceInstance providers = loadBalancerClient.choose("providers");
        //负载均衡的默认算法是轮询，轮询取得服务
        URI uri = URI.create(String.format("http://%s:%s", providers.getHost(), providers.getPort()));
        return uri.toString();
    }

    /*2整合eureka */
    @RequestMapping("/eurekaConsumer")
    public String eurekaConsumer() throws ExecutionException, InterruptedException {
        return restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody();
    }

    /**
     * 整合 hystrix
     * @return
     */
    @RequestMapping(value = "hystrix")
    public String hystrix(){
        return helloService.helloService();
    }
}
